package com.stylefeng.guns.modular.vpn_exclusive_line_manage.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.common.constant.DatasourceEnum;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.modular.system.model.VpnPackageInfo;
import com.stylefeng.guns.modular.system.model.VpnServer;
import com.stylefeng.guns.modular.system.model.VpnUserInfo;
import com.stylefeng.guns.modular.vpn.utils.LogUtil;
import com.stylefeng.guns.modular.vpn.utils.TimeUtil;
import com.stylefeng.guns.modular.vpn.vo.Paging;
import com.stylefeng.guns.modular.vpn_exclusive_line_manage.dao.ExclusiveLineMapper;
import com.stylefeng.guns.modular.vpn_exclusive_line_manage.entity.ExclusiveLineDO;
import com.stylefeng.guns.modular.vpn_exclusive_line_manage.dto.PackageDTO;
import com.stylefeng.guns.modular.vpn_exclusive_line_manage.entity.ExclusiveLinePackageDO;
import com.stylefeng.guns.modular.vpn_exclusive_line_manage.entity.ExclusiveLineUserDO;
import com.stylefeng.guns.modular.vpn_exclusive_line_manage.entity.VpnServerDO;
import com.stylefeng.guns.modular.vpn_exclusive_line_manage.service.IVpnExclusiveLineService;
import com.stylefeng.guns.modular.vpn_package_info.service.IVpnPackageInfoService;
import com.stylefeng.guns.modular.vpn_server_info.service.IVpnServerService;
import com.stylefeng.guns.modular.vpnuserinfo.service.IVpnUserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class VpnExclusiveLineServiceImpl implements IVpnExclusiveLineService {

    @Resource
    private ExclusiveLineMapper lineMapper;

    @Resource
    private IVpnServerService serverService;

    @Resource
    private IVpnUserInfoService userInfoService;

    @Resource
    private IVpnPackageInfoService packageInfoService;

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public Paging<ExclusiveLineDO> list(Integer page, Integer size) {
        Integer start = (page > 0 ? page - 1 : 0) * size;
        Paging<ExclusiveLineDO> paging = new Paging<>();
//        paging.setTotal(lineMapper.findTotalCount().longValue());
        paging.setItems(lineMapper.findList(start,size));
        return paging;
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public void addPackageOfUser(PackageDTO dto) {
        //1、检测添加服务器是否存在
        EntityWrapper<VpnServer> serverWrapper = new EntityWrapper<>();
        serverWrapper.eq("server_id",dto.getServerId());
        serverWrapper.eq("server_type",2);
        serverWrapper.eq("status",1);
        VpnServer vpnServer = serverService.selectOne(serverWrapper);
        if (vpnServer == null){
            throw new GunsException(BizExceptionEnum.EXCLUSIVE_SERVER_NOT_EXIST);
        }
//        dto.setServerId(vpnServer.getId());

        Date dt = new Date();
        dto.setStartTime(dt);

        Calendar c = Calendar.getInstance();
        c.setTime(dt);
        c.add(Calendar.DATE, dto.getAvailableDays());
        dt = c.getTime();

        dto.setEndTime(dt);
        dto.setStatus(1);

        String[] userNameArr = dto.getUserName().split(",");

        if (userNameArr.length < 1){
            throw new GunsException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        List<PackageDTO> items = new ArrayList<>();

        EntityWrapper<VpnPackageInfo> pwrapper = new EntityWrapper<>();
        pwrapper.eq("package_Type",2);
        VpnPackageInfo packageInfo = packageInfoService.selectOne(pwrapper);

        dto.setPackageId(packageInfo.getId());

        for (int i = 0;i<userNameArr.length;i++){
            //2、检测用户是否存在
            EntityWrapper<VpnUserInfo> userWrapper = new EntityWrapper<>();
            userWrapper.eq("username",userNameArr[i]);
            VpnUserInfo userInfo = userInfoService.selectOne(userWrapper);
            if (userInfo == null){
                throw new GunsException(BizExceptionEnum.USER_NOT_EXISTED);
            }

            PackageDTO item = new PackageDTO();
            BeanUtils.copyProperties(dto,item);
            item.setUserId(userInfo.getId());

            //3、生成订单号，添加用户套餐
            item.setOrderNo(generateOrder());

            items.add(item);
        }

        lineMapper.addExclusivePackage(items);

        LogUtil.saveOperationLog("专属线路增加用户",
                "专属线路："+vpnServer.getServerIp()+", 套餐服务时间："+TimeUtil.dateToGTMString(dto.getStartTime(),"yyyy-MM-dd HH:mm:ss")+" - "
                        +TimeUtil.dateToGTMString(dto.getStartTime(),"yyyy-MM-dd HH:mm:ss")+"， 用户名："+dto.getUserName());

    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public void deletePackage(String serverId,String userId) {
        Integer count = lineMapper.findPackageCount(serverId,userId);
        if (count < 1){
            throw new GunsException(BizExceptionEnum.EXCLUSIVE_PACKAGE_NOT_EXIST);
        }
        lineMapper.deleteExclusivePackage(serverId,userId);
    }

    /**
     * 修改专属线路下的用户名单
     * @param serverId
     * @param userNames
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public void update(Integer serverId, String userNames) {
        //1、检测添加服务器是否存在
        EntityWrapper<VpnServer> serverWrapper = new EntityWrapper<>();
        serverWrapper.eq("server_id",serverId);
        serverWrapper.eq("server_type",2);
        serverWrapper.eq("status",1);
        VpnServer vpnServer = serverService.selectOne(serverWrapper);
        if (vpnServer == null){
            throw new GunsException(BizExceptionEnum.EXCLUSIVE_SERVER_NOT_EXIST);
        }

        String[] userNameArr = new String[]{};
        if (!StringUtils.isEmpty(userNames.trim())){
            userNameArr = userNames.trim().split(",");
        }

        ExclusiveLinePackageDO packageDO = lineMapper.findExclusiveLinePackage(serverId);

        if (packageDO == null){
            throw new GunsException(BizExceptionEnum.EXCLUSIVE_PARAMS_ERROR);
        }

        List<PackageDTO> items = new ArrayList<>();

        PackageDTO packageDTO = new PackageDTO();
        packageDTO.setServerId(serverId);
        packageDTO.setStartTime(packageDO.getStartTime());
        packageDTO.setEndTime(packageDO.getEndTime());
        packageDTO.setPackageId(packageDO.getPackageId());
        packageDTO.setStatus(1);

        if (userNameArr.length >0){
            for (int i = 0;i<userNameArr.length;i++){
                //2、检测用户是否存在
                EntityWrapper<VpnUserInfo> userWrapper = new EntityWrapper<>();
                userWrapper.eq("username",userNameArr[i]);
                VpnUserInfo userInfo = userInfoService.selectOne(userWrapper);
                if (userInfo == null){
                    throw new GunsException(BizExceptionEnum.USER_NOT_EXISTED);
                }

                PackageDTO item = new PackageDTO();
                BeanUtils.copyProperties(packageDTO,item);
                item.setUserId(userInfo.getId());

                //3、生成订单号，添加用户套餐
                item.setOrderNo(generateOrder());
                items.add(item);
            }
        }

        lineMapper.deleteExclusivePackageByServerId(serverId);

        LogUtil.saveOperationLog("更新专属线路",
                "专属线路："+vpnServer.getServerIp()+", 套餐服务时间："+
                        TimeUtil.dateToGTMString(packageDTO.getStartTime(),"yyyy-MM-dd HH:mm:ss") +" - "+TimeUtil.dateToGTMString(packageDTO.getEndTime(),"yyyy-MM-dd HH:mm:ss"));

        if(items.size() > 0){
            lineMapper.addExclusivePackage(items);
        }
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public ExclusiveLineDO findExclusiveLinePackage(Integer serverId) {
        return lineMapper.findExclusiveLine(serverId);
    }

    /**
     * 可用专属服务器列表
     * @return
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public List<VpnServerDO> serverList() {
        return lineMapper.findEnableExclusiveServer();
    }

    public static String generateOrder() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
        String dateString = format.format(new Date());
        int randomNum = (int)(Math.random() * 100000);
        return String.format("A%s%06d", dateString, randomNum);
    }
}
